package org.runtimedao.template;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

public class DAOMethod {

	private String signature;
	private String name;
	private String query;
	private String[] params;
	private boolean returnsCollection;

	public DAOMethod(Method method, String query) {
		this.query = query;
		this.name = method.getName();
		buildSignature(method);
		buildParams(method);
		setReturnType(method);
	}

	private void buildSignature(Method method) {
		StringBuilder signature = new StringBuilder();
		signature.append("public ");
		signature.append(method.getReturnType().getName());
		signature.append(" ");
		signature.append(method.getName());
		signature.append("(");

		Class<?>[] params = method.getParameterTypes();

		for (int i = 0; i < params.length; i++) {
			Class<?> param = params[i];
			signature.append(param.getName());
			signature.append(" p");
			signature.append(i + 1);
			if (!(i + 1 == params.length)) {
				signature.append(", ");
			}
		}

		signature.append(")");
		this.signature = signature.toString();
	}

	private void buildParams(Method method) {
		params = new String[method.getParameterTypes().length];
		for (int i = 0; i < params.length; i++) {
			params[i] = "p" + (i + 1);
		}
	}

	private void setReturnType(Method method) {
		Class<?> returnType = method.getReturnType();
		if (Collection.class.isAssignableFrom(returnType)
				|| Map.class.isAssignableFrom(returnType)) {
			returnsCollection = true;
		} else {
			returnsCollection = false;
		}
	}

	public String getName() {
		return name;
	}

	public String getSignature() {
		return signature;
	}

	public String getHql() {
		return query;
	}

	public String[] getParams() {
		return params;
	}

	public boolean isReturnsCollection() {
		return returnsCollection;
	}
}
